CODE 61. Simplify Path

版权声明:本文为博主原创文章,转载请注明出处,谢谢!

版权声明:本文为博主原创文章,转载请注明出处:http://blog.jerkybible.com/2013/10/06/2013-10-06-CODE 61 Simplify Path/

访问原文「CODE 61. Simplify Path

Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"

click to show corner cases.
Corner Cases:

  • Did you consider the case where path = "/../"?
    In this case, you should return "/".
  • Another corner case is the path might contain multiple slashes '/' together,
    such as "/home//foo/".
    In this case, you should ignore redundant slashes and return "/home/foo".
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
public String simplifyPath(String path) {
// Start typing your Java solution below
// DO NOT write main() function
if (null == path || "".equals(path) || !path.startsWith("/")) {
return "";
}
List<String> pathList = new ArrayList<String>();
char[] paths = path.toCharArray();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < paths.length; i++) {
if (paths[i] == '/') {
if (!sb.toString().equals("")) {
if (!sb.toString().equals(".")
&& !sb.toString().equals("..")) {
pathList.add(sb.toString());
} else if (sb.toString().equals("..")) {
if (!pathList.isEmpty()) {
pathList.remove(pathList.size() - 1);
}
}
sb = null;
sb = new StringBuilder();
}
} else {
sb.append(paths[i]);
}
}
if (!sb.toString().equals("")) {
if (!sb.toString().equals(".") && !sb.toString().equals("..")) {
pathList.add(sb.toString());
} else if (sb.toString().equals("..")) {
if (!pathList.isEmpty()) {
pathList.remove(pathList.size() - 1);
}
}
}
if (pathList.isEmpty()) {
return "/";
} else {
sb = null;
sb = new StringBuilder();
for (String s : pathList) {
sb.append("/" + s);
}
return sb.toString();
}
}
Jerky Lu wechat
欢迎加入微信公众号